<template>
  <div>
    <el-dialog
      :title="info.isAdd ? '添加商品' : '修改商品'"
      :visible.sync="info.isShow"
      width="60%"
      @close="cancel"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="一级分类" prop="first_cateid">
              <el-select
                v-model="ruleForm.first_cateid"
                placeholder="请选择"
                @change="firstChange"
              >
                <el-option
                  v-for="(item, index) in firstList"
                  :key="index"
                  :label="item.catename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级分类" prop="second_cateid">
              <el-select v-model="ruleForm.second_cateid" placeholder="请选择">
                <el-option
                  v-for="(item, index) in secondList"
                  :key="index"
                  :label="item.catename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="goodsname">
              <el-input v-model="ruleForm.goodsname"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="ruleForm.price"></el-input>
            </el-form-item>
            <el-form-item label="市场价格" prop="market_price">
              <el-input v-model="ruleForm.market_price"></el-input>
            </el-form-item>
            <el-form-item label="商品图片" prop="img">
              <!-- //action: 上传文件的地址-->
              <!-- list-type：文件列表的类型 文字 照片墙 -->
              <!-- on-remove：移除图片时调用的函数 -->
              <!-- on-changes：文件修改的时候的钩子函数 -->
              <!-- on-exceed:超出限制时的钩子函数 -->
              <!-- file-list:已上传的文件列表 -->
              <!-- on-preview：预览时的钩子 -->
              <el-upload
                action="#"
                list-type="picture-card"
                :on-remove="handleRemove"
                :on-change="handleChange"
                :auto-upload="false"
                :file-list="fileList"
                :limit="1"
                :on-exceed="limitImg"
                :on-preview="handlePictureCardPreview"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <el-form-item label="商品规格" prop="specsid">
              <el-select v-model="ruleForm.specsid" placeholder="请选择">
                <el-option label="顶级分类" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in cateList"
                  :key="index"
                  :label="item.catename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="规格属性值" prop="specsattr">
              <el-select v-model="ruleForm.specsattr" placeholder="请选择">
                <el-option label="顶级分类" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in cateList"
                  :key="index"
                  :label="item.catename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否新品" prop="isnew">
              <!-- label的值需要是数字，因此加上冒号，保证是变量 -->
              <el-radio v-model="ruleForm.isnew" :label="1">是</el-radio>
              <el-radio v-model="ruleForm.isnew" :label="2">否</el-radio>
            </el-form-item>
            <el-form-item label="是否热卖" prop="ishot">
              <!-- label的值需要是数字，因此加上冒号，保证是变量 -->
              <el-radio v-model="ruleForm.ishot" :label="1">是</el-radio>
              <el-radio v-model="ruleForm.ishot" :label="2">否</el-radio>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <!-- label的值需要是数字，因此加上冒号，保证是变量 -->
              <el-radio v-model="ruleForm.status" :label="1">正常</el-radio>
              <el-radio v-model="ruleForm.status" :label="2">禁用</el-radio>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="详细描述" name="second">
          <div id="editor"></div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submitForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
//引入富文本编辑器
import E from "wangeditor";
import {
  goodsAdd,
  goodsedit,
  getCatelistTree,
  getSecondCatelist,
} from "../../request";
let defaultData = {
  first_cateid: 1,
  second_cateid: 2,
  goodsname: "",
  price: "",
  market_price: "",
  img: "",
  specsid: "",
  specsattr: "",
  isnew: 1,
  ishot: 1,
  status: 1,
};
export default {
  props: {
    info: {
      type: Object,
      default: {
        isAdd: false,
        isShow: false,
      },
    },
  },
  data() {
    return {
      //表单数据
      ruleForm: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      //图片
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      // 面板
      activeName: "second",
      //表单规则
      rules: {
        second_cateid: [
          { required: true, message: "一级分类必填", trigger: "blur" },
        ],
        first_cateid: [
          { required: true, message: "二级分类必填", trigger: "blur" },
        ],
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [
          { required: true, message: "请输入市场价格", trigger: "blur" },
        ],
        specsid: [
          { required: true, message: "请输入商品规格", trigger: "blur" },
        ],
        specsattr: [
          { required: true, message: "请输入商品规格属性值", trigger: "blur" },
        ],
      },
      //下拉菜单数据
      cateList: [],
      firstList: [],
      secondList: [],
      hasEditor: false,
      editor: {},
    };
  },
  created() {
    //获取分类列表(一级)
    this.getList();
  },
  mounted() {},
  methods: {
    //面板
    handleClick(tab, event) {
      //点击标签页的切换
      if (tab.name === "second" && !this.hasEditor) {
        this.editor = new E(document.getElementById("editor"));
        this.editor.create();
        this.hasEditor = true;
        // 重新设置编辑器内容
        this.editor.txt.html(this.ruleForm.description);
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let fd = new FormData();
          for (let k in this.ruleForm) {
            fd.append(k, this.ruleForm[k]);
          }
          //封装请求
          let res;
          //获取富文本编辑器中的内容
          this.ruleForm.description = this.editor.txt.html();
          if (this.info.isAdd) {
            res = goodsAdd(fd);
          } else {
            res = goodsedit(fd);
          }

          if (res) {
            this.cancel();
            // 兄弟组件传值，告诉list组件更新
            this.$bus.$emit("update");
          }
        } else {
          return false;
        }
      });
    },
    async getList() {
      let res = await getCatelistTree();
      this.firstList = res.list;
    },
    //一级分类的数据变化
    async firstChange() {
      let id = this.ruleForm.first_cateid;
      let res = await getSecondCatelist(id);
      this.secondList = res.list;
    },
    //删除图片的监听
    handleRemove() {
      this.ruleForm.img = "";
    },
    //修改文件时触发
    handleChange(file, fileList) {
      // 给img赋值，传给fd
      this.ruleForm.img = fileList[0].raw;
    },
    //上传文件的控件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    limitImg() {
      this.$message.warning("分类图片最多添加一个");
    },
    //设置当前组件状态
    setStatus(val) {
      this.ruleForm = { ...val };
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //取消按钮
    cancel() {
      // 重置弹窗中得数据
      this.ruleForm = { ...defaultData };
      //清理文件列表
      this.fileList = [];
      // 关闭弹窗
      this.info.isShow = false;
    },
  },
};
</script>

<style>
.cell img {
  width: 100px;
  height: 50px;
}
#editor {
  width: 100%;
  height: 200px;
}
</style>